﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ElectronicDiary.ViewModels;

namespace ElectronicDiary.Helpers
{
    public static class HtmlHelpers
    {
        public static MvcHtmlString PageLinks(this HtmlHelper html,
            PagingInfo pagingInfo, Func<int, string> pageUrl)
        {
            StringBuilder result = new StringBuilder();
            for (int i = 1; i <= pagingInfo.TotalPages; i++)
            {
                TagBuilder tag = new TagBuilder("a"); // Construct an <a> tag
                tag.MergeAttribute("href", pageUrl(i));
                tag.InnerHtml = i.ToString();
                if (i == pagingInfo.CurrentPage)
                    tag.AddCssClass("selected");
                result.Append(tag.ToString());
            }
            return MvcHtmlString.Create(result.ToString());
        }

        public static MvcHtmlString GradeDescr(this HtmlHelper htlm,
            string descr, int linelenght)
        {
            StringBuilder sb = new StringBuilder();

            string[] words = descr.Split(new char [] {' '});
            bool nextline = false;

            sb.Append(words[0] + " " );
            for (int i = 1; i < words.Length; i++)
            {
                if(!nextline)
                {
                    if (sb.Length + words[i].Length <= linelenght)
                        sb.Append(words[i] + " ");
                    else 
                    {
                        nextline = true;
                        sb.Append("<br />");
                        i--;
                    }
                }
                else
                {
                    int tmp = sb.ToString().LastIndexOf("<br />") + 6;
                    if (sb.Length - tmp + words[i].Length <= linelenght)
                        sb.Append(words[i] + " ");
                    else
                    {
                        sb.Remove(sb.Length - 1, 1);
                        sb.Append("...");
                        break;
                    }
                }
            }

            return MvcHtmlString.Create(sb.ToString());
        }
    }
}